package com.example.feidaolumanager.viewModel

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.feidaolumanager.Constants
import com.example.feidaolumanager.api.RetrofitClient
import kotlinx.coroutines.launch

class AgentViewModel : ViewModel() {

    var agentState by mutableStateOf(AgentState())
        private set

    fun getAgents() {
        viewModelScope.launch {
            try {
                val responseDTO = RetrofitClient.agentService.getAgents()
                if (responseDTO.code == Constants.success_code) {
                    responseDTO.data?.let { agents ->
                        val list = arrayListOf<String>()
                        agents.forEach {
                            list.add(it.agent_name)
                        }
                        agentState = AgentState(
                            agents = agents,
                            agents_name = list
                        )
                    }
                }
            } catch (e: Exception) {
                // 正确处理异常，而不是再次抛出
                e.printStackTrace()
                // 可以在这里添加更多错误处理逻辑，例如更新UI状态以显示错误信息
                Log.e("test", e.message.toString())
                agentState = agentState.copy(
                    errorMsg = e.message
                )
            }
        }
    }
}